#!/usr/bin/env python
import os
import inkex,simplestyle
from lxml import etree
# from OrigamiHelper import stylesheet

class AddStylesheet(inkex.Effect):
    """Add Origami Stylesheet on the current svg file"""
    def __init__(self):
        """ main stream"""
        inkex.Effect.__init__(self)
        self.NSS = {
            u'sodipodi'    :u'http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd',
            u'cc'        :u'http://web.resource.org/cc/',
            u'svg'        :u'http://www.w3.org/2000/svg',
            u'dc'        :u'http://purl.org/dc/elements/1.1/',
            u'rdf'        :u'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
            u'inkscape'    :u'http://www.inkscape.org/namespaces/inkscape',
            u'xlink'    :u'http://www.w3.org/1999/xlink'
}

    
    def effect(self) :
        """Add the stylesheet  """
        name = "default"
        file = os.path.abspath(os.path.join(".inkscape/extensions/OrigamiHelper","svg",name+".svg"))
        path = "//svg:defs[1]"
        f = etree.parse(file)
        old_defs = self.current_layer.xpath(path, self.NSS)[0]
        
        # Check if the stylesheet is already inserted
        if old_defs.get("id") == "origami_stylesheet" :
            #TODO check if the stylesheet is the same
            pass
        else :
            self.current_layer.remove(old_defs)        
            self.style = f.xpath(path, self.NSS)[0]
            self.current_layer.insert(1,self.style)
  

# Create effect instance and apply it.
Effect = AddStylesheet()
Effect.affect()